import {AsyncStorage} from 'react-native'
import Request from "../utils/Request";
import constant from "../utils/constant";
import {kAuthorization} from "../constant";
import {ActiveModel, AuthModel} from "./model";
import RouterServer from "../utils/RouterServer";

const {Toast} = require('antd-mobile');
const STORAGE_KEY = "STORAGE_KEY_active";
const model = {
    namespace: 'active',
    state: {
        loading: false,
        list: null,
        typeList: null,
        userJoinedActiveList: [],
        selectedActiveTypes: [],


        activeDetail: null,
    },
    reducers: {
        save(state, {payload}) {
            return {...state, ...payload}
        }
    },
    effects: {

        // 保存到本地
        * saveToStorage({payload}, {call}) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload))
        },

        // 本地恢复
        * restoreFromStorage({payload}, {call, put, select}) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
            yield put({
                type: 'save',
                payload: {...JSON.parse(data)}
            });
        },

        //获取列表
        * fetchList({payload}, {call, put, select}) {
            const auth: AuthModel = yield select(state => state.auth);
            yield put({type: 'save', payload: {loading: true}});
            payload['userId'] = auth.userInfo.id;
            payload['Authorization'] = auth.token_type + ' ' + auth.access_token;
            payload['ids'] = payload['ids'];
            const result: activeList = yield call(Request.get, Request.getApi().filterActiveList, payload);
            yield put({type: 'save', payload: {loading: false}});
            if (result) {
                yield put({type: 'save', payload: {list: result}});
            }
        },

        //加入或离开活动
        * joinOrLeaveActive({payload}, {put, select, call}) {
            const auth: AuthModel = yield select(state => state.auth);
            const active: ActiveModel = yield select(state => state.active);
            if (!payload.from) {
                const act: activeItem = payload.active;
                const param = {
                    Authorization: auth.token_type + ' ' + auth.access_token,
                    params: {userId: auth.userInfo.id, activityId: act.activity.id}
                };
                param['Content-Type'] = `application/json`;

                let index = active.list.content.indexOf(act);
                const isJoin = act['isJoin'] === '0' ? '1' : '0';
                const res = yield call(Request.post, Request.getApi().joinActive + `/${isJoin}`, param);
                if (res) {
                    act.isJoin = isJoin;
                    active.list.content[index] = act;
                    yield put({type: 'save', payload: {...active}});
                    let tip = isJoin === '1' ? '您已经加入该活动!' : '您已经离开该活动';
                    Toast.success(tip, constant.ToastDuration);
                }

                yield put({type: 'fetchUserActiveList'});
            } else if (payload.from === 'myActives') {
                const act: activity = payload.active;
                const param = {
                    Authorization: auth.token_type + ' ' + auth.access_token,
                    params: {userId: auth.userInfo.id, activityId: act.id}
                };
                param['Content-Type'] = `application/json`;

                let index = active.userJoinedActiveList.indexOf(act);
                const isJoin = act['isJoin'] === '0' ? '1' : '0';
                const res = yield call(Request.post, Request.getApi().joinActive + `/${isJoin}`, param);
                if (res) {
                    act.isJoin = isJoin;
                    active.userJoinedActiveList[index] = act;
                    active.activeDetail = act;
                    yield put({type: 'save', payload: {...active}});
                    let tip = isJoin === '1' ? '您已经加入该活动!' : '您已经离开该活动';
                    Toast.success(tip, constant.ToastDuration);
                }
                yield put({type: 'fetchUserActiveList'});
            }
        },


        //获取活动类型列表
        * fetchTypeList({payload}, {put, call, select}) {
            const auth: AuthModel = yield select(state => state.auth);
            let active: ActiveModel = yield select(state => state.active);
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            const result: activeTypeList = yield call(Request.get, Request.getApi().activeTypeList, payload);
            if (result) {
                if (payload.loadmore) {
                    let content = active.typeList.content;
                    active.typeList = result;
                    active.typeList.content = content.concat(result.content);
                } else {
                    active.typeList = result;
                }
                yield put({type: 'save', payload: {...active}})
            }
        },


        //获取用户参加的活动列表
        * fetchUserActiveList({payload}, {put, call, select}) {
            yield put({type: 'save', payload: {userJoinedActiveList: []}});
            const auth: AuthModel = yield select(state => state.auth);

            let p = {};
            p[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            const userJoinedActiveList = yield call(Request.get, Request.getApi().userJoinedActiveList + `/${auth.userInfo.id}`, p);
            if (userJoinedActiveList && Array.isArray(userJoinedActiveList)) {
                yield put({
                    type: 'save',
                    payload: {userJoinedActiveList}
                })
            }
        },

        * applyActiveFilter({payload}, {put, call, select}) {
            yield put({
                type: 'save',
                payload: {selectedActiveTypes: payload.selectedActiveTypes}
            });
            const active: ActiveModel = yield select(state => state.active);

            if (active.selectedActiveTypes.length > 0) {
                yield put({
                    type: 'fetchList',
                    payload: {
                        pi: 1,
                        ps: 10,
                        ids: active.selectedActiveTypes.join(',')
                    }
                });
            } else {
                yield put({type: 'clear'});
            }
            yield put({type: 'fetchUserActiveList'});
            yield call(RouterServer.pop)
        },


        * goToDetail({payload}, {put, call}) {
            yield put({
                type: 'save',
                payload
            });
            yield call(RouterServer.push, 'activeDetail');
        },

        //清除数据
        * clear({payload}, {put}) {
            yield put({
                type: 'save', payload: {
                    activeList: null,
                }
            })
        }

    },
    subscriptions: {
        setup({dispatch}) {

        }
    },
};


export default model;
